<template>
	<van-popup v-model:show="visible" position="right" :style="{ height: '100%', width: '100%' }" class="notice-detail-page" @close="handleClose">
		<!-- 详情页加载状态 - 居中显示 -->
		<div v-if="loading" class="detail-loading-container">
			<van-loading type="spinner" color="#1989fa" vertical> 加载中... </van-loading>
		</div>

		<div class="notice-content" v-show="!loading">
			<div class="title-card">
				<div class="icon-tip"></div>
				<span class="title-detail">{{ noticeInfo.noticeTitle }}</span>
			</div>
			<div class="sub-title">
				<div>
					来源: <span class="text-value">{{ noticeInfo.createBy }}</span>
				</div>
				<div class="sub-title-text">
					时间: <span class="text-value">{{ noticeInfo.createTime }}</span>
				</div>
			</div>
			<div class="main-text-content" v-html="noticeInfo.noticeContent"></div>

			<!-- 附件下载 -->
			<div class="file-dowm-list" v-if="fileList.length > 0">
				<div class="title-card mb20">
					<div class="icon-tip"></div>
					<span>附件</span>
				</div>
				<div class="file-list-container" v-for="(item, index) in fileList" :key="index">
					<van-row>
						<van-col span="15">
							{{ item.name }}
						</van-col>
						<van-col span="9" class="down-button-col" @click="handleDownload(item)">
							<span class="down-button">下载</span>
						</van-col>
					</van-row>
				</div>
			</div>

			<!-- 底部关闭按钮 -->
			<div class="bot-close-icon" @click="handleClose">
				<van-icon name="clear" size="24" />
			</div>

			<!-- 底部已阅按钮 -->
			<div class="bot-read-icon" :class="{ readed: isReaded }" @click="handleMarkRead">
				<img src="https://wx.ksepia.com/profile/mini-image/view-read.png" class="read-icon-img" />
				<span class="bot-read-view-text">已阅({{ readCount }})</span>
			</div>
		</div>
	</van-popup>
</template>

<script>
import { ref, reactive, watch } from 'vue'
import { showToast, showLoadingToast, closeToast } from 'vant'
import { addNoticeReadRecord, selectReadCountByNoticeId, isReaded as checkIsReaded, getFileList } from '@/api/notice'

export default {
	name: 'NoticeDetail',
	props: {
		show: {
			type: Boolean,
			default: false,
		},
		noticeData: {
			type: Object,
			default: () => ({}),
		},
	},
	emits: ['update:show', 'close', 'read-status-change'],
	setup(props, { emit }) {
		const visible = ref(false)
		const loading = ref(false)
		const noticeInfo = reactive({
			noticeId: '',
			noticeTitle: '',
			noticeContent: '',
			createBy: '',
			createTime: '',
		})
		const fileList = ref([])
		const isReaded = ref(false)
		const readCount = ref(0)

		// 监听显示状态
		watch(
			() => props.show,
			(newVal) => {
				visible.value = newVal
				if (newVal && props.noticeData.noticeId) {
					loadNoticeDetail()
				}
			}
		)

		// 监听弹窗关闭
		watch(visible, (newVal) => {
			emit('update:show', newVal)
		})

		// 加载通知详情
		const loadNoticeDetail = async () => {
			Object.assign(noticeInfo, props.noticeData)
			loading.value = true

			try {
				// 检查是否已读并自动标记
				await checkReadStatus(noticeInfo.noticeId)

				// 获取已读数量
				await getReadCount(noticeInfo.noticeId)

				// 获取附件列表
				await loadFileList(noticeInfo.noticeId)
			} catch (error) {
				console.error('获取通知详情失败:', error)
				showToast('获取通知详情失败')
			} finally {
				loading.value = false
			}
		}

		// 检查已读状态
		const checkReadStatus = async (noticeId) => {
			try {
				const res = await checkIsReaded({ id: noticeId })
				console.log('>>>>>>是否已阅读', res)

				if (res.data > 0) {
					isReaded.value = true
				} else {
					isReaded.value = false
					// 自动标记为已读
					await handleMarkRead()
				}
			} catch (error) {
				console.error('检查已读状态失败:', error)
			}
		}

		// 获取已读数量
		const getReadCount = async (noticeId) => {
			try {
				const res = await selectReadCountByNoticeId({ id: noticeId })
				console.log('>>>>>>阅读数量', res)
				readCount.value = res.data || 0
			} catch (error) {
				console.error('获取已读数量失败:', error)
			}
		}

		// 加载附件列表
		const loadFileList = async (noticeId) => {
			try {
				const res = await getFileList(noticeId)
				if (res.code === '0') {
					const files = res.data || []
					fileList.value = files.map((item) => ({
						id: item.id,
						url: item.url,
						name: item.originalFileName,
						wjlx: item.fileExtension,
					}))
				}
			} catch (error) {
				console.error('获取附件列表失败:', error)
				fileList.value = []
			}
		}

		// 处理关闭
		const handleClose = () => {
			visible.value = false
			// 重置数据
			Object.keys(noticeInfo).forEach((key) => {
				noticeInfo[key] = ''
			})
			fileList.value = []
			isReaded.value = false
			readCount.value = 0
			emit('close')
		}

		// 处理文件下载
		const handleDownload = (item) => {
			const loadingToast = showLoadingToast({
				message: '下载中...',
				forbidClick: true,
			})

			try {
				// H5 环境下载文件
				const link = document.createElement('a')
				link.href = item.url
				link.download = item.name
				link.target = '_blank'
				document.body.appendChild(link)
				link.click()
				document.body.removeChild(link)

				showToast('开始下载')
			} catch (error) {
				console.error('下载文件失败:', error)
				showToast('下载失败')
			} finally {
				closeToast()
			}
		}

		// 处理标记已读
		const handleMarkRead = async () => {
			console.log('是否已阅：', isReaded.value)
			if (isReaded.value) {
				return
			}

			isReaded.value = true

			try {
				const params = {
					noticeId: noticeInfo.noticeId,
				}
				await addNoticeReadRecord(params)

				// 更新已读数量
				await getReadCount(noticeInfo.noticeId)

				// 通知父组件已读状态改变
				emit('read-status-change', noticeInfo.noticeId)
			} catch (error) {
				console.error('标记已读失败:', error)
				showToast('操作失败')
				isReaded.value = false
			}
		}

		return {
			visible,
			loading,
			noticeInfo,
			fileList,
			isReaded,
			readCount,
			handleClose,
			handleDownload,
			handleMarkRead,
		}
	},
}
</script>

<style lang="less" scoped>
.notice-detail-page {
	/* 详情页面loading居中 */
	.detail-loading-container {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 1001;
	}

	.notice-content {
		padding: 20px;
		height: 100%;
		overflow-y: auto;
		position: relative;
		background: #fff;

		.title-card {
			display: flex;
			align-items: center;
			margin-bottom: 16px;

			.icon-tip {
				width: 4px;
				height: 16px;
				background: #1989fa;
				margin-right: 8px;
				border-radius: 2px;
			}
		}

		.title-detail {
			font-size: 18px;
			font-weight: bold;
			color: #323233;
			line-height: 1.4;
		}

		.sub-title {
			margin: 16px 0;
			font-size: 12px;
			color: #969799;
			line-height: 1.5;

			.sub-title-text {
				margin-top: 4px;
			}

			.text-value {
				color: #323233;
			}
		}

		.main-text-content {
			line-height: 1.6;
			margin: 20px 0;
			color: #646566;
			font-size: 14px;

			:deep(p) {
				margin: 0 0 16px 0;
			}
		}

		.file-dowm-list {
			margin-top: 24px;

			.mb20 {
				margin-bottom: 20px;
			}

			.file-list-container {
				padding: 12px;
				background: #f7f8fa;
				border-radius: 8px;
				margin-bottom: 8px;

				.down-button-col {
					text-align: right;

					.down-button {
						color: #1989fa;
						font-size: 14px;
						cursor: pointer;
					}
				}
			}
		}

		/* 底部关闭按钮 */
		.bot-close-icon {
			position: fixed;
			right: 10px;
			top: 10px;
			z-index: 1000;
			width: 40px;
			height: 40px;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;

			.van-icon {
				color: #7a7a7a;
			}
		}

		/* 底部已阅按钮 - 椭圆形 */
		.bot-read-icon {
			position: fixed;
			bottom: 30px;
			right: 20px;
			height: 40px;
			min-width: 100px;
			padding: 0 20px;
			background: #1989fa;
			border-radius: 20px;
			box-shadow: 0 4px 20px rgba(25, 137, 250, 0.3);
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
			transition: all 0.3s ease;
			color: #fff;

			.read-icon-img {
				width: 16px;
				height: 16px;
				margin-right: 6px;
				filter: brightness(0) invert(1);
			}

			.bot-read-view-text {
				font-size: 14px;
				font-weight: 500;
				white-space: nowrap;
			}

			&.readed {
				background: #1989fa;
				color: #fff;

				.read-icon-img {
					filter: brightness(0) invert(1);
				}
			}
		}
	}
}
</style>
